/**
 * 2009-12-23 下午09:00:21 
 * esignature
 * com.smc.dao.impl
 * CertificationDaoImpol
 */
package com.smc.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.smc.dao.CertificationDao;
import com.smc.domain.model.Certification;
import com.smc.domain.model.User;

/** 
 * @author chenheng
 * @version 0.0.1
 */
public class CertificationDaoImpol extends HibernateDaoSupport implements CertificationDao {

	/* (non-Javadoc)
	 * @see com.smc.dao.CertificationDao#saveCertificate(com.smc.domain.model.Certification)
	 */
	@SuppressWarnings("unchecked")
	public void saveCertificate(Certification cert) {
		String hql = "SELECT a.uuid FROM Certification a WHERE a.user = ?";
		Session session = getSession();
		User user = (User) session.load(User.class, cert.getUserUuid());
		Query query = session.createQuery(hql);
		query.setParameter(0, user);
		List<Certification> list = query.list();
		if ( list.size() != 0) {
			return ;
		}
		cert.setUser(user);
		session.saveOrUpdate(cert);
		session.flush();
	}

	public int countCertification(boolean authorized) {
		String hql = "SELECT COUNT(a.id) FROM Certification a WHERE a.authorized = ?";
		Long count = (Long) getHibernateTemplate().find(hql, authorized).iterator().next();
		return count.intValue();
	}

	@SuppressWarnings("unchecked")
	public List<Certification> listCertification(boolean authorized, int pageIndex, int pageSize) {
		String hql = "FROM Certification a JOIN FETCH a.user WHERE a.authorized = ? ";
		Session session = getSession();
		Query query = session.createQuery(hql);
		query.setParameter(0, authorized);
		query.setFirstResult((pageIndex - 1)*pageSize);
		query.setMaxResults(pageSize);
		List<Certification> list = query.list();
		return list;
	}

	public void deleteCertification(String uuid) {
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		Object cert = session.load(Certification.class, uuid);
		session.delete(cert);
		session.flush();
		tx.commit();
		
	}

	public Certification getCertByUuid(String uuid) {
		Certification cert = (Certification) getHibernateTemplate().get(Certification.class, uuid);
		return cert;
	}

	public void updateCertification(Certification cert) {
		getHibernateTemplate().update(cert);
	}

	@SuppressWarnings("unchecked")
	public Certification getCertByAlias(String alias) {
		String hql = "FROM Certification c WHERE c.alias = ? AND c.authorized = ? ";
		Object[] params = new Object[]{alias,true};
		List<Certification> l = getHibernateTemplate().find(hql, params);
		Certification cert = null ;
		if ( l.size() > 0 ) {
			cert = l.iterator().next();
		}
		return cert;
	}

}

